<?php
/**
 * Created by PhpStorm.
 * User: hongls
 * Date: 2016/3/31
 * Time: 9:56
 */
namespace Wap\Controller;
use Common\Model\CouponModel;
use Common\Model\ThirdCouponModel;
use Common\Model\UtilsModel;
use Wap\BaseController;
class CardController extends BaseController{
    /**
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     */
    public function index(){
        redirect(U('Card/cardList'));
    }


    /**
     * storelist 适用门店列表
     */
    public function storelist(){

        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $store = M('s_store',null,DB_MAIN_CFG);
        $region = M('cfg_region',null,DB_MAIN_CFG);
        //获取卡券id
        $cardId = I('get.cardId',null);
        //获取可适用门店id
        $storeId = $card_info->where('id='.$cardId)->getField('storeId');
        //获取所有门店基本信息
        $list = $store->where("FIND_IN_SET(id,'".$storeId."')")->select();
        foreach($list as $key => $value){
            $list[$key]['city'] = $region->where('area_id='.$value['city'])->getField('name');
            $list[$key]['district'] = $region->where('area_id='.$value['district'])->getField('name');
            //合并地址
            $list[$key]['address'] = $list[$key]['city'].$list[$key]['district'].$list[$key]['address'];
        }

        $uid=session("uid")+0;
        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->assign('list',$list);
        $this->smarty->display('Card/storelist.html');
    }


    /**
     * ajaxConsume ajaxa核销函数
     */
    public function ajaxConsume(){
        $jobNum = I('post.jobNum',null);
        $code = I('post.code',null);
        $restaurantId = I('post.restaurantId',null);
        $cardId = I('post.cardId',null);
        $time = getdate(time());
        $day = $time['wday'];
        
        $card_code = M('card_code',null,DB_MAIN_CFG);
        $verification = M('s_verification',null,DB_MAIN_CFG);
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $store = M('s_store',null,DB_MAIN_CFG);
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);

        $verificationItem = $verification->where('jobNum=\''.$jobNum . '\' and restaurantId='.$restaurantId)->find();
        if(empty($verificationItem)){
            $data['status'] = AJAX_FASLE;
            $data['msg'] = '该核销员不存在';
            $this->ajaxReturn($data);
        }
        $storeId = $verification->where('jobNum='.$jobNum)->getField('storeId');

        $restaurantName = $restaurant->where('id='.$restaurantId)->getField('restaurantName');
        $storeName = $store->where('id='.$storeId)->getField('storeName');

        $card_list_item = $card_code->where('code='.$code . ' and restaurantId = '.$restaurantId)->find();


        //判断该卡券是否已经被使用
        if($card_list_item['status'] == CouponModel::CODE_STATUS_USED){
            $data['status'] = AJAX_FASLE;
            $data['msg'] = '该卡券已经被使用';
            $this->ajaxReturn($data);
        }

        //获取该卡券的有效期
//        if(empty($card_list_item['beginTimestamp'])){
//            $endTime = $card_list_item['receiveTimestamp'] + $card_list_item['fixedBeginTerm']*24*60*60+$card_list_item['fixedTerm']*24*60*60;
//        }else{
//            $endTime = $card_list_item['endTimestamp'];
//        }
        if($card_list_item['endTimestamp'] < time()){
            $data['status'] = AJAX_FASLE;
            $data['msg'] = '卡券已过期';
            $this->ajaxReturn($data);
        }

        $card_info_item = $card_info->where('id='.$card_list_item['cardId'].' and  FIND_IN_SET('.$day.',availableDay) ')->find();
        if(empty($card_info_item)){
            $data['status'] = AJAX_FASLE;
            $data['msg'] = '该日无法使用该卡券';
            $this->ajaxReturn($data);
        }

        $card_storeId = explode(',',$card_info_item['storeId']);
        if(!in_array($storeId,$card_storeId)){
            $data['status'] = AJAX_FASLE;
            $data['msg'] = '该门店无法核销该卡券';
            $this->ajaxReturn($data);
        }

        $consume_log_data = array(
            'code' => $code,
            'consumeTime'=>time(),
            'consumeFrom' =>CouponModel::CARD_CONSUME_FROM_MYSELF,
            'jobNum' => $jobNum,
            'restaurantId' => $restaurantId,
            'storeId' => $storeId,
            'restaurantName'=>$restaurantName,
            'storeName' => $storeName,
            'cardTitle'=> $card_info_item['title'],
            'cardType' => $card_info_item['type'],
        );
        //添加核销记录
        $consume_log->add($consume_log_data);
        //更改卡券的使用状态
        $card_code->data('status='.CouponModel::CODE_STATUS_USED)->where('code='.$code)->save();
        $verification->setInc('verifyNum');
        $data['status'] = AJAX_SUCCESS;
        $data['msg'] = '核销成功';
        $this->ajaxReturn($data);

    }

    //自平台卡券详情
    private function selfCodeDetail($autoId){
        $id = $autoId;
        $card_code      = M('card_code',null,DB_MAIN_CFG);
        $card_base      = M('card_base_info',null,DB_MAIN_CFG);
        $restaurant     = M('s_restaurant',null,DB_MAIN_CFG);

        $item           = $card_code->find($id);
        $card_base_item = $card_base->field('desc,notice,availableDay')->find($item['cardId']);
        $phone          = $restaurant->field('phone')->find($item['restaurantId']);
        //合并和卡券基础信息
        $item = array_merge($item,$card_base_item);
        //合并电话
        $item = array_merge($item,$phone);
//        if(!empty($item['fixedTerm'])){
//            $item['endTimestamp'] =  $item['receiveTimestamp'] + $item['fixedBeginTerm']*24*60*60+$item['fixedTerm']*24*60*60;
//            $item['beginTimestamp'] = $item['receiveTimestamp'] + $item['fixedBeginTerm']*24*60*60;
//        }
        //替换可用时间 更好的前端用户交互
        if($item['availableDay'] == '0,1,2,3,4,5,6'){
            $item['availableDay'] = '周一至周日';
        }
        else{
            //替换可用时间
            $item['availableDay'] = str_replace('1','周一', $item['availableDay']);
            $item['availableDay'] = str_replace('2','周二', $item['availableDay']);
            $item['availableDay'] = str_replace('3','周三', $item['availableDay']);
            $item['availableDay'] = str_replace('4','周四', $item['availableDay']);
            $item['availableDay'] = str_replace('5','周五', $item['availableDay']);
            $item['availableDay'] = str_replace('6','周六', $item['availableDay']);
            $item['availableDay'] = str_replace('0','周日', $item['availableDay']);
        }

        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_DEFAULT);
        $this->smarty->assign('CODE_STATUS_RECEIVED',CouponModel::CODE_STATUS_RECEIVED);
        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_USED);
        $this->smarty->assign('CODE_STATUS_OUTDATE',CouponModel::CODE_STATUS_OUTDATE);
        $this->smarty->assign('CODE_STATUS_SEND',CouponModel::CODE_STATUS_SEND);
        $this->smarty->assign('CODE_STATUS_DELETE',CouponModel::CODE_STATUS_DELETE);

        $uid=session("uid")+0;
        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->assign('obj',$item);
        $this->smarty->display('Card_v2/info.html');
    }

    /**
     * 第三方外部券
     * Author: shijy
     * @param $autoId
     */
    private function thirdCouponDetail($autoId){
        $id = $autoId;
        $card_code      = M('third_coupon',null,DB_MAIN_CFG);
        $item           = $card_code->find($id);



        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_DEFAULT);
        $this->smarty->assign('CODE_STATUS_RECEIVED',CouponModel::CODE_STATUS_RECEIVED);
        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_USED);
        $this->smarty->assign('CODE_STATUS_OUTDATE',CouponModel::CODE_STATUS_OUTDATE);
        $this->smarty->assign('CODE_STATUS_SEND',CouponModel::CODE_STATUS_SEND);
        $this->smarty->assign('CODE_STATUS_DELETE',CouponModel::CODE_STATUS_DELETE);


        $this->smarty->assign('reserveURL',C('RESERVE_URL').$item['tid']);
        $this->smarty->assign('obj',$item);
        if($item['couponType']==ThirdCouponModel::COUPON_TYPE_CASH){
            $this->smarty->display('Card/info_thirdcoupon_cash.html');
        }else{
            $this->smarty->display('Card/info_thirdcoupon_item.html');
        }


    }

    /**
     * info 卡券基本信息
     */
    public function info(){
        $id             = I('get.id'.null);
        $table         = I('get.table',null);

        switch ($table){
            case 'code':
                $this->selfCodeDetail($id);
                break;
            case 'thirdcoupon':
                $this->thirdCouponDetail($id);
                break;
            default:
                $this->error("错误的卡券");
                die;
        }
    }



    /**
     * consume 自主核销界面
     */
    public function selfConsume(){

        $id = I('get.id',null);
        $card_code = M('card_code',null,DB_MAIN_CFG);
        $item = $card_code->find($id);
        $restaurant=CouponModel::getOneRestaurant($item['restaurantId']);
        $item['photo'] = $restaurant['photo'];

        $uid=session("uid")+0;
        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->assign('obj',$item);
        $this->smarty->display('Card/selfConsume.html');
    }

    /**
     *商户微信核销页面
     * Author: shijy
     */
    public function shopConsume(){
        UtilsModel::checkLogin();
        $uid=session('uid')+0;
        $verificationReturn=CouponModel::getVerificationByUid($uid);
        if($verificationReturn['status']==2){
            $this->error($verificationReturn['msg'],u('User/bind?url='.urlencode(u('Card/shopConsume'))));
        }
        if($verificationReturn['status']!=0){
            $this->error($verificationReturn['msg']);
        }


        session('restaurantId',$verificationReturn['data']['restaurantId']);
        session('storeId',$verificationReturn['data']['storeId']);
        session('jobNum',$verificationReturn['data']['jobNum']);

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->display('Card/shopConsume_query.html');
    }

    /**
     * 商户核销
     * Author: shijy
     */
    public function shopConsume_queryResult(){
        UtilsModel::checkLogin();
        $uid=session('uid')+0;
        $verificationReturn=CouponModel::getVerificationByUid($uid);
        if($verificationReturn['status']!=0){
            $this->error($verificationReturn['msg']);
        }


        $code=I('post.code',null);
        if(!$code){
            $this->error('请指定卡券号');
        }



        $codeReturn=CouponModel::getCodeInfo($code);
        if($codeReturn['status']!=0){
            $this->error($codeReturn['msg']);
        }

            $checkReturn=CouponModel::checkCodeConsumeAble($code,session('storeId'),session('restaurantId'));

            $codeReturn['canConsume']=$checkReturn['status'];
            $codeReturn['reason']=$checkReturn['msg'];


        $this->smarty->assign('code',$code);
        $this->smarty->assign('cardTitle',$codeReturn['data']['cardTitle']);
        $this->smarty->assign('begin',$codeReturn['data']['beginTimestamp']);
        $this->smarty->assign('end',$codeReturn['data']['endTimestamp']);

        $this->smarty->assign('canConsume',$checkReturn['status']);
        $this->smarty->assign('reason',$checkReturn['msg']);

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->display('Card/shopConsume_queryResult.html');

    }


    /**
     * 商户核销
     * Author: shijy
     */
    public function shopConsume_do(){
        UtilsModel::checkLogin();
        $uid=session('uid')+0;
        $verificationReturn=CouponModel::getVerificationByUid($uid);
        if($verificationReturn['status']!=0){
            $this->error($verificationReturn['msg']);
        }

        $code=I('get.code','');
        if(!$code){
            $this->error('请指定卡券号');
        }
        $this->ajaxReturn(CouponModel::shopConsumeCode($uid,$code));
    }


    /**
     * 商户核销
     * Author: shijy
     */
    public function shopConsume_log(){

        UtilsModel::checkLogin();
        $uid=session('uid')+0;
        $verificationReturn=CouponModel::getVerificationByUid($uid);
        if($verificationReturn['status']!=0){
            $this->error($verificationReturn['msg']);
        }
        $verification=$verificationReturn['data'];
        if($verification['restaurantId']==0){
            $restaurantName='-';
        }else{
            $restaurant=CouponModel::getOneRestaurant($verification['restaurantId']);
            $restaurantName=$restaurant['restaurantName'];
        }
        
        if($verification['storeId']==0){
            $storeName='-';
        }else{
            $store=CouponModel::getOneStore($verification['storeId']);
            $storeName=$store['storeName'];
        }

        $this->smarty->assign('uid',$uid);
        $this->smarty->assign('verificationName',$verification['verificationName']);
        $this->smarty->assign('jobNum',$verification['jobNum']);
        $this->smarty->assign('storeName',$storeName);
        $this->smarty->assign('restaurantName',$restaurantName);
        $this->smarty->assign('verifyNum',$verification['verifyNum']);

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $data=CouponModel::getCodeList(null,null,$verification['id'],CouponModel::CODE_STATUS_USED,0,10);
        $this->smarty->assign('list',$data['list']);

        $this->smarty->display('Card/shopConsume_log.html');
    }


    public function shopConsume_log_ajax(){
        $page = I('get.page',2,'intval');

        $uid=session('uid')+0;
        if(!$uid){
            $this->ajaxReturn(array('status'=>0, 'dataHTML'=>'请登陆'));
        }
        $verificationReturn=CouponModel::getVerificationByUid($uid);
        if($verificationReturn['status']!=0){
            $this->ajaxReturn(array('status'=>0, 'dataHTML'=>'非核销员，无权查看'));
        }

        $data=CouponModel::getCodeList(null,null,$verificationReturn['data']['id'],CouponModel::CODE_STATUS_USED,$page,10);
        $this->smarty->assign('list',$data['list']);
        $html=$this->smarty->fetch('Card/shopConsume_log_item.html');
        $this->ajaxReturn(array('status'=>0, 'dataHTML'=>$html, 'isPage'=>$data['nextPage']));
    }

    /**
     * list 卡券列表
     */
    public function cardList(){
        UtilsModel::checkLogin();
        $uid=session("uid");
        $list=CouponModel::getMyUserfullCardList($uid,1,C('LIST_PAGE_SIZE'));
        $this->smarty->assign('list',$list['data']);
        $this->smarty->assign('nextPage',$list['nextPage']);
        $this->smarty->assign('title','我的卡券');

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->display('Card_v2/list.html');
    }
    /**
     * 下拉加载更多 当前卡券列表
     */
    public function cardListMore(){
        UtilsModel::checkLogin();
        $p      = I('post.page',2,'int');
        $uid    = session('uid');
        $list=CouponModel::getMyUserfullCardList($uid,$p,C('LIST_PAGE_SIZE'));

        $this->smarty->assign('list',$list['data']);
        $this->smarty->assign('CODE_STATUS_OUTDATE',CouponModel::CODE_STATUS_OUTDATE);
        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_USED);
        $result=array(
            'data'=>$this->smarty->fetch('Card/item.html'),
        );
        $this->ajaxReturn($result) ;
    }

    /**
     * history 历史记录
     */
    public function history(){
        UtilsModel::checkLogin();
        $uid=session("uid");
        $list=CouponModel::getMyHistoryList($uid,1,C('LIST_PAGE_SIZE'));


        $this->smarty->assign('CODE_STATUS_DEFAULT',CouponModel::CODE_STATUS_DEFAULT );   //卡券未使用
        $this->smarty->assign('CODE_STATUS_RECEIVED',CouponModel::CODE_STATUS_RECEIVED );   //被领取
        $this->smarty->assign('CODE_STATUS_USED',CouponModel::CODE_STATUS_USED );       //已经使用
        $this->smarty->assign('CODE_STATUS_OUTDATE',CouponModel::CODE_STATUS_OUTDATE );    //过期

        //是否当日首次签到
        signAssignWap($uid,$this->smarty);

        $this->smarty->assign('list',$list['data']);
        $this->smarty->assign('title','我的卡券 ');
        $this->smarty->display('Card_v2/history.html');
    }



    public function historyMore(){
        UtilsModel::checkLogin();
        $p=I('post.p',0,'int');
        $uid=session("uid");

        $list=CouponModel::getMyHistoryList($uid,$p,C('LIST_PAGE_SIZE'));

        $this->smarty->assign('list',$list['data']);
        $result=array(
            'data'=>$this->smarty->fetch('Card/item.html'),
        );
        $this->ajaxReturn($result) ;
    }
}
